package top.wilsonlv.jaguar.cloud.auth.extension.sms;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import top.wilsonlv.jaguar.cloud.auth.sdk.sms.SmsCode;
import top.wilsonlv.jaguar.cloud.auth.sdk.sms.SmsType;
import top.wilsonlv.jaguar.commons.web.response.JsonResult;

import javax.mail.MessagingException;
import javax.validation.constraints.NotBlank;
import java.io.IOException;


/**
 * @author lvws
 * @since 2022/1/7
 */
@Slf4j
@RestController
@RequestMapping(SmsApi.SMS_PATH)
@RequiredArgsConstructor
@Api(tags = "短信验证码API")
@ConditionalOnProperty(prefix = "jaguar.auth.sms", name = "enable", havingValue = "true")
public class SmsApi {

    public static final String SMS_PATH = "/sms";

    private final SmsService smsService;

    @ApiOperation(value = "发送邮箱验证码")
    @PostMapping("/email")
    public JsonResult<String> email(@RequestParam(required = false) String email,
                                    @RequestParam @NotBlank SmsType smsType) throws MessagingException, IOException {

        SmsCode smsCode = smsService.createSms(email, smsType);
        smsService.sendSms(smsCode);
        return JsonResult.success(smsCode.getTicket());
    }

    @ApiOperation(value = "发送短信验证码")
    @PostMapping("/phone")
    public JsonResult<String> phone(@RequestParam(required = false) String phone,
                                    @RequestParam @NotBlank SmsType smsType) {
        SmsCode smsCode = smsService.createSms(phone, smsType);

        //TODO 对接短信验证码平台

        return JsonResult.success(smsCode.getTicket());
    }


}
